package com.godofball.medtrack.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.godofball.medtrack.common.Result;
import com.godofball.medtrack.exception.PurchaseException;
import com.godofball.medtrack.pojo.Purchase;
import com.godofball.medtrack.service.PurchaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/purchase")
@Slf4j
public class PurchaseController {

    @Autowired
    private PurchaseService purchaseService;

    @GetMapping("/page")
    public Result<Page> page(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                             String purchaseId,
                             String manufacturerId,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date beginTime,
                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime) {
        log.info("page={},pageSize={},purchaseId={},beginTime={},endTime={}", page, pageSize, purchaseId, beginTime, endTime);
        Page<Purchase> purchasePage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Purchase> purchaseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        purchaseLambdaQueryWrapper.eq(StringUtils.hasLength(purchaseId),Purchase::getId,purchaseId);
        purchaseLambdaQueryWrapper.eq(StringUtils.hasLength(manufacturerId),Purchase::getManufacturerId,manufacturerId);
        purchaseLambdaQueryWrapper.between(beginTime!=null&&endTime!=null,Purchase::getCreateTime,beginTime,endTime);
        purchaseLambdaQueryWrapper.orderByDesc(Purchase::getUpdateTime);

        purchaseService.page(purchasePage,purchaseLambdaQueryWrapper);

        return Result.success(purchasePage);
    }

    /**
     * 生成进货表单
     * @param manufacturerId 产商编号
     * @param remark 备注
     * @return
     */
    @GetMapping
    public Result<String> add(@RequestParam("id") Long manufacturerId,String remark){
        log.info("manufacturerId={},remark={}",manufacturerId,remark);
        if (manufacturerId==null) throw new PurchaseException("产商编号不能为空");
        purchaseService.generatePurchase(manufacturerId, remark);
        return Result.success("生成进货单成功");
    }

}
